<template>
  <swiper
    :current="current"
    :autoplay="false"
    :disable-touch="!manualSwitch"
    @change="onChange"
    @touchstart="onTouchStart"
    @touchend="onTouchEnd"
    :style="{ height }"
  >
    <swiper-item
      v-for="(item, index) in list"
      :key="index"
      class="swiper-item"
      :class="{ 'active-video-item': current === index && item.type === 'video' }"
    >
      <image
        v-if="item.type === 'image'"
        :src="item.src"
        mode="aspectFill"
        class="media"
      />
      <video
        v-else-if="item.type === 'video'"
        :id="'swiper_Video_' + index"
        :src="item.src"
        :muted="muted"
        :initial-time="initialTime"
        :autoplay="false"
        :controls="false"
        :enable-progress-gesture="false"
        class="media"
        @ended="onVideoEnd"
        @loadedmetadata="onVideoMetadataLoaded"
      />
    </swiper-item>
  </swiper>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default: () => [],
    },
    // 轮播图高度
    height: {
      type: String,
      default: "300rpx",
    },
    // 图片切换时长，单位ms
    interval: {
      type: Number,
      default: 5000,
    },
    // 每张图片自动切换时长字段，设置后interval失效
    autoplayValue: {
      type: String,
      default: "",
    },
    // 视频静音播放
    muted: {
      type: Boolean,
      default: false,
    },
    // 视频播放结束是否自动切换下一张
    videoEndPlay: {
      type: Boolean,
      default: true,
    },
    // 是否允许手动滑动
    manualSwitch: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      current: 0,
      initialTime: 0, // 视频初始播放时间
      isManualSwiping: false,
      videoContext: null,
      timer: null,
      lastVideoIndex: -1,
    };
  },
  watch: {
    list(newVal) {
      this.current = 0;
      this.handleAutoSwitch();
    },
  },
  methods: {
    // 核心切换控制
    handleAutoSwitch() {
      clearTimeout(this.timer);
      if (!this.list.length) return;

      const currentItem = this.list[this.current];
      if (currentItem.type === "image") {
        let duration = this.autoplayValue
          ? (currentItem[autoplayValue] || 1) * 1000
          : this.interval;
        this.startTimer(duration);
      } else if (currentItem.type === "video") {
        this.initialTime = 0;
        this.initVideoContext();
        this.playCurrentVideo();
      }
    },

    // 初始化视频上下文
    initVideoContext() {
      this.videoContext = uni.createVideoContext(`swiper_Video_${this.current}`, this);
    },

    // 播放控制
    playCurrentVideo() {
      if (!this.videoContext) return;

      this.videoContext.play();
      this.pausePreviousVideo();
    },

    // 暂停前一个视频
    pausePreviousVideo() {
      if (this.lastVideoIndex !== -1 && this.lastVideoIndex !== this.current) {
        const prevVideo = uni.createVideoContext(
          `swiper_Video_${this.lastVideoIndex}`,
          this
        );
        prevVideo.pause();
      }
      this.lastVideoIndex = this.current;
    },

    // 启动定时器
    startTimer(customDuration) {
      this.timer = setTimeout(() => {
        this.nextSlide();
      }, customDuration || this.interval);
    },

    // 切换下一页
    nextSlide() {
      this.current = (this.current + 1) % this.list.length;
    },

    // 轮播切换回调
    onChange(e) {
      this.current = e.detail.current;
      this.handleAutoSwitch();
    },

    // 触摸开始处理
    onTouchStart() {
      if (!this.manualSwitch) return;
      clearTimeout(this.timer);
      this.isManualSwiping = true;
      if (this.list[this.current]?.type === "video") {
        this.videoContext?.pause();
      }
    },

    // 触摸结束处理
    onTouchEnd() {
      if (!this.manualSwitch) return;
      this.isManualSwiping = false;
      this.handleAutoSwitch();
    },

    // 视频元数据加载
    onVideoMetadataLoaded() {
      if (!this.videoEndPlay && this.videoContext) {
        const videoDuration = this.videoContext.duration * 1000;
        this.startTimer(videoDuration);
      }
    },

    // 视频播放结束
    onVideoEnd() {
      if (this.videoEndPlay) {
        this.nextSlide();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}
.media {
  width: 100%;
  height: 100%;
}
/* #ifdef H5 */
::v-deep .uni-video-video {
  width: 100% !important;
  background: transparent !important;
}
/* #endif */
/* #ifdef APP-PLUS */
::v-deep .uni-video-container {
  background: transparent !important;
  transform: translateX(-100%) !important;
  transition: all 0.3s !important;
  z-index: -1 !important;
  display: none;
}
::v-deep .active-video-item .uni-video-container {
  display: block !important;
}
/* #endif */
</style>
